﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Routing;
using System.Xml.Serialization;
using Smarly.Bussines.Model;
using Smarly.Web.App_Start;
using Smarly.Web.Controllers;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Smarly.Web.Controllers.Base;
using Smarly.Web.Helpers;

namespace Smarly.Web.Storage
{
	public static class Sitemap
	{
		static readonly CloudBlobContainer container;
		static Sitemap()
		{
#if !DEBUG
			CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureStorageConnectionString"].ConnectionString);
			CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
			container = blobClient.GetContainerReference("smarly");
			container.CreateIfNotExists();
			container.SetPermissions(new BlobContainerPermissions
			{
				PublicAccess = BlobContainerPublicAccessType.Blob
			});
#endif
		}

		public static void Init()
		{
			BaseController.SectionPublished += Update;
		}

		public static void Update(HttpRequestBase request)
		{
#if !DEBUG

			CloudBlockBlob blockBlob = container.GetBlockBlobReference("sitemap.xml");

			var ns = new XmlSerializerNamespaces();
			ns.Add("", "http://www.sitemaps.org/schemas/sitemap/0.9");
			ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");

			var obj = new SiteMapUrlSet();

			var routes = new RouteCollection();
			RouteConfig.RegisterRoutes(routes);
			foreach (var book in BookTree.GetFullTree())
			{
					obj.Urls.Add(new SiteUrl
												 {
													 Location = request.FullUrl(book.Url),
													 LastModifiedDate = book.UpdateDate,
												 });
			}

		
			using (var stream = new MemoryStream())
			{
				var ser = new XmlSerializer(typeof(SiteMapUrlSet));
				ser.Serialize(stream, obj, ns);
				stream.Flush();
				stream.Position = 0;
				blockBlob.UploadFromStream(stream);
				stream.Position = 0;
				using (FileStream fs = new FileStream(Path.Combine(request.MapPath("~/"), "Sitemap.xml"), FileMode.Create))
				{
					stream.CopyTo(fs);
				}
			}
#endif


		}

	}

	[XmlRoot("urlset", Namespace = "http://www.sitemaps.org/schemas/sitemap/0.9")]
	public class SiteMapUrlSet
	{
		[XmlAttribute("schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
		public string xsiSchemaLocation = "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd";

		private readonly List<SiteUrl> urls = new List<SiteUrl>();
		[XmlElement("url")]
		public List<SiteUrl> Urls { get { return urls; } }
	}

	public class SiteUrl
	{
		[XmlElement("loc")]
		public string Location { get; set; }

		[XmlElement("lastmod")]
		public string LastModified
		{
			get
			{
				string result = null;
				if (LastModifiedDate.HasValue)
				{
					result = LastModifiedDate.Value.ToString("yyyy-MM-ddTHH:mm:sszzz");
				}
				return result;
			}
			set
			{
				DateTime dateTime;
				if (DateTime.TryParse(value, out dateTime))
				{
					LastModifiedDate = dateTime;
				}
				else
				{
					LastModifiedDate = null;
				}
			}
		}

		[XmlIgnore]
		public DateTime? LastModifiedDate { get; set; }

		[XmlElement("changefreq")]
		public string ChangeFrequency { get; set; }

		public bool ShouldSerializeLastModified() { return LastModifiedDate.HasValue; }
	}
}